package com.tedu.zweibo.controller;

import com.tedu.zweibo.mapper.WeiboMapper;
import com.tedu.zweibo.pojo.dto.WeiboDTO;
import com.tedu.zweibo.pojo.entity.User;
import com.tedu.zweibo.pojo.entity.Weibo;
import com.tedu.zweibo.pojo.vo.WeiboDetailVO;
import com.tedu.zweibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/v1/weibo/")
@Api(tags = "微博模块")
@Validated
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;
    @PostMapping("insert")
    @ApiOperation("发微博")
    public int insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session){
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO,weibo);
        User user = (User)session.getAttribute("user");
        if (user==null){
            return 2;
        }
        weibo.setCreated(new Date());
        weibo.setUserId(user.getId());
        System.out.println(weibo);
        int insert = weiboMapper.insert(weibo);
        System.out.println(insert);
        return 1;
    }
    @GetMapping("selectIndex")
    @ApiOperation("查询全部微博")
    public List<WeiboIndexVO> selectIndex(){
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndexWeibo();
        return weiboIndexVOS;
    }
    @GetMapping("selectById")
    @ApiOperation("查询id微博")
    @ApiImplicitParam(value = "微博ID",name="id",required = true,example = "300")
    public WeiboDetailVO selectById(@Range(min = 1,max = 99999,message = "微博id必须在1-99999之间") @RequestParam Integer id) {
        if(id<=0){
            throw new IllegalArgumentException("微博id小于1");
        }
        return weiboMapper.selectById(id);
    }
}